package com.hps.demo.config;

import java.time.Duration;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;

/**
 * @author heps
 * @since 2020/7/13 20:25
 */
public class MyRedisCache extends RedisCacheManager {

  public MyRedisCache(RedisCacheWriter cacheWriter,
      RedisCacheConfiguration defaultCacheConfiguration) {
    super(cacheWriter, defaultCacheConfiguration);
  }

  @Override
  protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
    if (StringUtils.isBlank(name)) {
      throw new RuntimeException("cacheName cannot be null");
    }
    String[] cacheNameArr = StringUtils.split(name, "#");
    name = cacheNameArr[0];
    if (cacheNameArr.length > 1 && StringUtils.isNumeric(cacheNameArr[1])) {
      Long ttl = Long.parseLong(cacheNameArr[1]);
      cacheConfig = cacheConfig.entryTtl(Duration.ofSeconds(ttl));
    }
    return super.createRedisCache(name, cacheConfig);
  }
}
